package sg.edu.nus.iss.vmcs.system;

import java.util.HashMap;
import sg.edu.nus.iss.vmcs.abstraction.IServiceRepository;

/*
 * @author nyi nyi than
 */
public final class ServiceRepository implements IServiceRepository
{
	private HashMap<Class<?>, Object> serviceContainer = new HashMap<Class<?>, Object>();

	private static ServiceRepository serviceRepositoryInstance;

	private ServiceRepository()
	{
	}

	public static ServiceRepository GetInstance() //double checked locking singleton - just for fun.
	{
		if (serviceRepositoryInstance == null)
		{
			synchronized (ServiceRepository.class)
			{
				if (serviceRepositoryInstance == null)
					serviceRepositoryInstance = new ServiceRepository();
			}
		}
		return serviceRepositoryInstance;
	}

	@Override
	public <TRegisterAs, TService extends TRegisterAs> void addService(
			Class<TRegisterAs> registerType, TService serviceInstance)
	{
		if (!serviceContainer.containsKey(registerType))
		{
			serviceContainer.put(registerType, serviceInstance);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public <TService> TService getService(Class<TService> serviceType)
	{
		if (serviceContainer.containsKey(serviceType))
			return (TService) serviceContainer.get(serviceType);
		else
			return null;
	}

	
	@Override
	public <TService> boolean isExist(Class<TService> serviceType)
	{
		return serviceContainer.containsKey(serviceType);
	}

}
